package com.biz.primus.ms.commodity.dao.redis.keyword;

import com.biz.primus.base.redis.CrudRedisDao;
import com.biz.primus.base.redis.util.RedisUtil;
import com.biz.primus.ms.commodity.dao.ro.KeywordRo;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

/**
 * Created by aaa on 2017/6/2.
 */
@Repository
public class KeywordRedisDao extends CrudRedisDao<KeywordRo, Long> implements Serializable {
    @Override
    public void save(KeywordRo ro) {
        super.save(ro);
        String key = getIdxMappingKey();
        zadd(key, ro.getUpdateTimestamp(), String.format("%s:%s", ro.getId(), ro.getIdx()));
    }

    private String getIdxMappingKey() {
        return getKeyByParams("idx");
    }

    @Override
    public void delete(KeywordRo ro) {
        super.delete(ro);
        String key = getIdxMappingKey();
        zrem(key, String.format("%s:%s", ro.getId(), ro.getIdx()));
    }

    public List<String> getIdxs(){
        String key = getIdxMappingKey();
        final Set<byte[]> bytes = zRange(key, 0, -1);
        if(CollectionUtils.isNotEmpty(bytes)){
            return RedisUtil.bytesSetToStringList(bytes);
        }
        return Lists.newArrayList();
    }

}
